import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from '@/config/nprogress'
import { projectRouter, systemRoutes } from '@/routers/router'
import { getUserInfo } from '@/services/api'
import { menuCodeMap } from '@/config/permissionMap'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...projectRouter, ...systemRoutes],
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})
// 环境变量，构建后就会被替换调
const env = import.meta.env
// 是否开启菜单权限
const openPermission = false

async function initRoute(next: NavigationGuardNext, to: RouteLocationNormalized) {
  const userStore = useUserStore()
  // 根据权限列表过滤菜单
  const userRoutes = fitlerRouters(userStore.permissions, projectRouter, menuCodeMap)
  userStore.setUserMenu(openPermission ? userRoutes : projectRouter)

  const toCode = (menuCodeMap as any)[to.path]
  const homePath = '/home'
  if (to.path === '/') {
    next({
      path: homePath,
    })
    // 判断用户访问的路径是否有权限，可能是历史记录的路径，只判断projectRouter
  }
  else if (
    openPermission
    && ![homePath].includes(to.path)
    && findRouteConfig(projectRouter, to.path)
    && !userStore.permissions.find(per => per.functionCode === toCode)
  ) {
    next('/403')
  }
  else {
    next()
  }
}

/**
 * @description 路由拦截 beforeEach
 */
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  const cm_token = to.query.cm_token as string
  const storeToken = userStore.token
  const clientId = env.VITE_CLIENT_ID

  // 如果是门户跳转过来的，重新获取一次用户信息
  if (cm_token) {
    userStore.setToken(cm_token)
    getUserInfo({
      refresh_token: cm_token,
      clientId,
    })
      .then((res) => {
        const { userInfo, permissions = [] } = res.data
        userStore.setUserInfo({
          userName: userInfo?.loginName,
        })
        userStore.setPermissions(permissions)
        initRoute(next, to)
      })
      .catch(() => {
        next(false)
      })
  }
  else if (storeToken) {
    // 如果是登录过的，就直接进入，每次都init也问题不大
    await initRoute(next, to)
  }
  else if (!to.path.startsWith('/login')) {
    // 跳转到统一门户的登录
    if (env.MODE !== 'development')
      await initRoute(next, to)
      // location.href = env.VITE_PIPE_PATH
    else
      await initRoute(next, to)
  }
  else {
    next()
  }
})

/**
 * @description 路由跳转错误
 */
router.onError((error) => {
  NProgress.done()
  console.warn('路由错误', error.message)
})

/**
 * @description 路由跳转结束
 */
router.afterEach(() => {
  NProgress.done()
})

export default router
